# 文件名: main.py (已修正并增强)
import os
import sys
from config.config import *
from utils.robot_controller import PiperRobot
from utils.voice_assistant import DuplexVoiceAssistant
from utils.camera_controller import CameraController

def main():
    """
    程序主函数：组装并启动应用
    """
    os.environ['DASHSCOPE_LOGGING_LEVEL'] = 'WARNING'

    # --- 第1步：硬件初始化 ---
    print("--- 正在初始化硬件 ---")
    robot_controller = PiperRobot()
    camera_controller = CameraController(camera_index=CAMERA_INDEX)  # 初始化单例
    camera_controller.start_preview()  # 开启实时预览

    # --- 第2步：硬件连接检查 ---
    if not robot_controller.piper:
        camera_controller.cleanup()
        sys.exit(1)
    print("----------------------")

    # --- 第3步：软件与服务初始化 ---
    assistant = DuplexVoiceAssistant(
        robot_controller=robot_controller,
        camera_controller=camera_controller
    )                   
    
    # --- 第4步：启动应用 ---
    print("\n🎤 机器人启动...")
    
    # 启动主循环
    assistant.run()

    # --- 第5步：程序结束后的清理 ---
    print("\n--- 主程序即将退出，执行最终清理 ---")
    camera_controller.cleanup()
    robot_controller.cleanup()
    print("👋 程序已安全关闭。")


if __name__ == "__main__":
    main()